import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutterlib/common/constants/constants.dart';
import 'package:flutterlib/common/net/dao_result.dart';
import 'package:flutterlib/common/net/retrofit/post_api.dart';
import 'package:flutterlib/common/style/quhui_style.dart';
import 'package:flutterlib/model/interest/interest_bean.dart';
import 'package:flutterlib/model/interest/interest_join.dart';
import 'package:flutterlib/pages/interest/viewmodel/interest_store.dart';
import 'package:flutterlib/widgets/bussiness/post/post_simple_list_item.dart';
import 'package:flutterlib/widgets/image/load_image.dart';
import 'package:flutterlib/widgets/pull/nested/simple_pull_load_manger.dart';
import 'package:flutterlib/widgets/pull/nested/simple_pull_load_page_widget.dart';
import 'package:loading/indicator/ball_beat_indicator.dart';
import 'package:loading/loading.dart';
import 'package:mobx/mobx.dart';
import 'package:flutterlib/common/utils/utils.dart';

class Page extends StatefulWidget {
  final int interestId;

  Page({
    Key key,
    this.interestId,
  }) : super(key: key);

  @override
  PageState createState() => PageState();
}

///页面 KeepAlive ，同时支持 动画Ticker
class PageState extends State<Page> with TickerProviderStateMixin {
  SimplePullLoadManger manger;
  final SettingsStore store =
      Provider.of<SettingsStore>(currentContext, listen: false);

  getDataLogic(int page) async {
    print(page);

    var posts = await PostApi.builder().pageByQuery(
        page - 1, 20, "createTime,desc", 0, widget.interestId, "");
    interestStore.setInterestPostCount(posts.totalElements);
    return new DataResult(posts.content, true);
  }

  Widget renderItem(index, post) {
    return PostSimpleListItem(post, onPressed: () {
      NavigatorUtils.goPostDetail(context, post.id, name: '');
    });
  }

  @override
  List<Widget> renderHeader(BuildContext context, bool innerBoxIsScrolled) {
    return <Widget>[
      SliverToBoxAdapter(
        child: Container(
          width: double.infinity,
          height: 150.h,
          color: QuhuiColors.white,
          child: Stack(
            children: [
              SizedBox(
                width: double.infinity,
                height: 132.h,
                child: LoadImage(
                  getInterestFromId(widget.interestId).groupLogo,
                  fit: BoxFit.cover,
                ),
              ),
              Positioned(
                top: 20.h,
                left: 10.w,
                child: MyBackButton(
                  color: Colors.black,
                ),
              ),
              Positioned(
                top: 88.h,
                left: 20.w,
                child: SizedBox(
                  width: 60.w,
                  height: 60.h,
                  child: LoadImage(
                    getInterestFromId(widget.interestId).groupLogo,
                    fit: BoxFit.fill,
                  ),
                ),
              ),
              Positioned(
                top: 88.h,
                left: 85.w,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Text(
                          _interestBean.name,
                          style: QuhuiConstant.largeTextWhiteBold,
                        ),
                        SizedBox(width: 5,),
                        Text(
                          '成员${_interestBean.userCount}  文章${interestStore.interestPostCount ?? 0}',
                          style: QuhuiConstant.smallTextWhite,
                        )
                      ],
                    ),
                    _buildInterestBtn(context),


                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    ];
  }

  Widget _buildInterestBtn(BuildContext context) {
    return Observer(
      builder: (_) {
        var interests = store.interests;
        var interest = interests.filter((element) => element.id == widget.interestId).firstOrNull;

        return interest == null
            ? FlatButton(
                color: QuhuiColors.mainThemeColor,
                highlightColor: Colors.green[700],
                colorBrightness: Brightness.dark,
                splashColor: Colors.grey,
                padding: EdgeInsets.all(0),
                child: Text(
                  "+兴趣",
                  style: QuhuiConstant.smallTextWhite,
                ),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20.0)),
                onPressed: () {
                  if (!isLogin) {
                    NavigatorUtils.goLogin(context);
                    return;
                  }
                  InterestJoin join =
                      InterestJoin(interestId: widget.interestId);
                  interestStore.joinInterest(join).then((value){
                    if(value){
                      store.addInterest(getInterestFromId(widget.interestId));
                    }else{
                      ToastUtils.error("加入失败");
                    }
                  });
                },
              )
            : FlatButton(
                color: QuhuiColors.mainThemeColor,
                highlightColor: Colors.green[700],
                colorBrightness: Brightness.dark,
                splashColor: Colors.grey,
                padding: EdgeInsets.all(0),
                child: Text(
                  "已加入",
                  style: QuhuiConstant.smallTextWhite,
                ),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20.0)),
                onPressed: () {},
              );
      },
    );
  }

  InterestStore interestStore = new InterestStore();
  InterestBean _interestBean;

  @override
  void initState() {
    super.initState();
    manger = SimplePullLoadManger.needSliverHeader(
      getDataLogic: getDataLogic,
      renderItem: renderItem,
      renderHeader: renderHeader,
    );
    interestStore.fetchInterest(widget.interestId);
  }

  @override
  Widget build(BuildContext context) {
    return Observer(
      builder: (_) {
        if (interestStore.interestFuture.status == FutureStatus.fulfilled) {
          _interestBean = interestStore.interestFuture.result;
          return Scaffold(
            body: SimplePullLoadWidget(
              pullLoadManger: manger,
            ),
          );
        } else {
          return new Scaffold(
            body: Container(
              color: QuhuiColors.white,
              child: Center(
                child: Loading(
                    indicator: BallBeatIndicator(),
                    size: 20.0,
                    color: QuhuiColors.mainThemeColor),
              ),
            ),
          );
        }
      },
    );
  }
}
